package com.queue.cli.util;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import java.io.*;
import java.util.PropertyResourceBundle;
import java.util.ResourceBundle;

public class ResourceUtils {
    private static final Logger logger = LoggerFactory.getLogger(ResourceUtils.class);
    /**
     * 属性文件全名
     */
    private static final String PROPERTY_FILE =System.getProperty("user.dir")+ File.separator+"conf"+File.separator+"queue-cli.properties";
    /**
     * 对应于属性文件的文件对象变量
     */
    private static File m_file = null;
    /**
     * 属性文件的最后修改日期
     */
    private static long m_lastModifiedTime = 0;

    private static ResourceBundle resourceBundle;

    private static BufferedInputStream inputStream;

    static {
        try {
            m_file = new File(PROPERTY_FILE);
            m_lastModifiedTime = m_file.lastModified();
            inputStream =  new BufferedInputStream(new FileInputStream(PROPERTY_FILE));
            resourceBundle = new PropertyResourceBundle(inputStream);
        }catch (FileNotFoundException e){
            e.printStackTrace();
        }catch (IOException e){
            e.printStackTrace();
        }
    }

    public static String getKey(String key){
        long newTime = m_file.lastModified();
        if (newTime>m_lastModifiedTime){
            try {
                m_lastModifiedTime = m_file.lastModified();
                inputStream = new BufferedInputStream(new FileInputStream(PROPERTY_FILE));
                resourceBundle = new PropertyResourceBundle(inputStream);
                inputStream.close();
            }catch (FileNotFoundException e) {
                logger.error("配置文件queue-cli.properties不存在");
                e.printStackTrace();
            } catch (IOException e) {
                logger.error("系统启动失败");
                e.printStackTrace();
            }
        }
        String result = resourceBundle.getString(key);

        return result;
    }

}
